package com.cwz.mq.ack.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cwz.core.utils.date.DateUtils;
import com.cwz.core.utils.string.StringUtils;
import com.cwz.core.utils.uuid.IdUtils;
import com.cwz.mq.ack.constant.MsgLogConstants;
import com.cwz.mq.ack.entity.MsgLog;
import com.cwz.mq.ack.mapper.MsgLogMapper;
import com.cwz.mq.ack.service.MsgLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 消息投递日志 服务实现类
 * </p>
 *
 * @author Wen
 * @since 2023-06-14
 */
@Service
public class MsgLogServiceImpl extends ServiceImpl<MsgLogMapper, MsgLog> implements MsgLogService {
	@Autowired
	private MsgLogMapper msgLogMapper;

	@Override
	public void insertMsg(MsgLog msgLog) {
		this.msgLogMapper.insert(msgLog);
	}

	@Override
	public void updateMsgStatus(String msgId, Integer status) {
		MsgLog msgLog = new MsgLog();
		msgLog.setStatus(status);
		this.msgLogMapper.update(msgLog, new UpdateWrapper<MsgLog>()
			.eq("msg_id", msgId));
	}

	@Override
	public void addMsgTryCount(String msgId, Integer tryCount) {
		if (StringUtils.isNull(tryCount)) {
			tryCount = this.selectByMsgId(msgId).getTryCount();
		}
		MsgLog msgLog = new MsgLog();
		msgLog.setTryCount(tryCount + 1);
		this.msgLogMapper.update(msgLog, new UpdateWrapper<MsgLog>()
			.eq("msg_id", msgId));
	}

	@Override
	public List<MsgLog> selectDeliverFail() {
		return this.msgLogMapper.selectList(new QueryWrapper<MsgLog>()
			.eq("status", MsgLogConstants.DELIVER_FAIL)
			.or(i -> i.ge("try_count", MsgLogConstants.MAX_TRY_COUNT)));
	}

	@Override
	public MsgLog selectByMsgId(String msgId) {
		return this.msgLogMapper.selectOne(new QueryWrapper<MsgLog>()
			.eq("msg_id", msgId));
	}
}
